var dt_selector;
var dt_unit;

$(document).ready(function() {
	init();
} );

//初始化
function init()
{
    //find out the row of name
    $('table tr th').each(function(index, data){
        console.log(data);
        if( data.innerText == 'Name' ){
			var row = $(data.parentElement);
			var table_selector = create_detail(row, { name:'Selector', holder:'selector-holder', id:'selector-table'});
			var table_unit = create_detail(row, { name:'Unit', holder:'unit-holder', id:'unit-table'});
			show_units(table_unit, table_selector);
        }
    });
}

function create_detail(row, config)
{
	var new_row = $('<tr><th class="col-lg-2 col-md-2 col-sm-2">'+config.name+'</th><td><div class="'+config.holder+'"><div></td></tr>');
	var table = $('<table id="'+config.id+'" class="display" style="width:100%"><thead><tr></tr></thead></table>');
	new_row.find("."+config.holder).append(table);
	new_row.insertAfter(row);
	return table;
}

function show_units(unit_table, selector_table)
{
	init_table_header(unit_table, ['Name','Black','Temp','ReadMe', '']);
	//load data
	$.ajax({url:"/profile/units?_flt_0_profile="+getShowID(),success:function(result){
		var dataSet = [];
		var titles = ['Weight','Selector'];
		result.result.forEach(function(item, index, arr){
			dataSet.push([item.name, item.black, item.temp, item.readme,
			    html_actions({edit:{onclick:'edit_unit('+item.id+')'},
			                    remove:{
			                        text:'删除unit',
                                    link:'/checkunitview/delete/'+item.id,
                                    title:'title',
			                    }
			                    })]);
			titles.push(item.name);
		});
		dt_unit = unit_table.DataTable( {
			data: dataSet,
			dom: 'l<"toolbar">frtip',
            fnInitComplete: function(){
                // $(".toolbar").css("width", "200px").css("display", "inline").css("margin-left", "10px");
                $('.unit-holder div.toolbar').html('<a class="btn btn-default btn-sm add">Add</a>');
                $('.unit-holder .toolbar .add').on('click', function(e){
                    console.log(e);
                    var profile = getShowID();
                    if( profile != null ){
                        // window.open("/checkunitview/add?profile="+profile);
                        window.location.href = "/checkunitview/add?profile=" + profile;
                    }
                });
            }

            /*
			"dom": "l<'#toolbar'>frtip",

			initComplete: function () {
                //表格加载完毕，手动添加按钮到表格上
                $("#toolbar").css("width", "100px").css("display", "inline").css("margin-left", "10px");
                $("#toolbar").append("我有问题");
                $("#toolbar").append("DIY");
                $("#toolbar").append("查看已解决问题");
                $("#toolbar").append("查看本实例代码");
                //查看本例子代码
                $(".viewCode").click(function(){
                    //显示模态框展示代码
                        $("#issueTableCode").modal("show");
                        $("#issueTableCodeContent").html($("#issueTableScript").html());
                });
            }
            */
		} );
		//show the table of selector
		titles.push('op');
		show_selectors(selector_table, titles);
	}});
}


function show_selectors(table, titles)
{
	init_table_header(table, titles);
	//load data
	$.ajax({url:"/profile/selectors?_flt_0_profile="+getShowID(),success:function(result){
		var dataSet = prepare_data_for_selectors(result.result, titles);
		dt_selector = table.DataTable( {
			data: dataSet,
			dom: 'l<"toolbar">frtip',
            fnInitComplete: function(){
                // $(".toolbar").css("width", "200px").css("display", "inline").css("margin-left", "10px");
                $('.selector-holder div.toolbar').html('<a class="btn btn-default btn-sm add-selector">Add</a>');
                $('.selector-holder .toolbar .add-selector').on('click', function(e){
                    console.log(e);
                    var profile = getShowID();
                    if( profile != null ){
                        // window.open("/checkunitview/add?profile="+profile);
                        window.location.href = "/selectorview/add?profile=" + profile;
                    }
                });
				/*
				$('.selector-holder .condition').mouseenter(function(e){
					var holder = $(e.target).find('.condition-actions');
					holder.show();
				});
				$('.selector-holder .condition').mouseleave(function(e){
					var holder = $(e.target).find('.condition-actions');
					holder.hide();
				});
				*/
            }
		} );
	}});
}

function prepare_data_for_selectors(rows, titles)
{
    var dataSet = [];
    rows.forEach(function(row, index, arr){
        console.log(row);
        var dataRow = new Array(titles.length);
        dataRow[0] = row['selector.weight'];
        dataRow[1] = row['selector.name'];

        for(var i=2; i<titles.length; i++){
            if( i == titles.length-1 ){
                var conf = {
                        edit:{onclick:'edit_selector('+row['selector.id']+')'},
                        remove:{
                            text:'删除Selector',
                            link:'/selectorview/delete/'+row['selector.id'],
                            title:'title',
                        }
                };
			    dataRow[i] = html_actions(conf);
			}else if( (i-2) < row.conditions.length ){
                dataRow[i] = condition_to_html(row.conditions[i-2]);
            }else {
                var link = ['<a ',
                    'class="btn btn-default btn-sm add-selector" ',
                    'onclick="add_condition('+row['selector.id']+');"',
                    '>',
                    'Add',
                    '</a>'
                ].join('');
                dataRow[i] = link;
            }
        }
        dataSet.push(dataRow);
    });
	return dataSet;
}

function condition_to_html(cond)
{
    var conf = {
    edit:{onclick:'edit_condition('+cond.id+','+cond['unit.id']+','+cond['selector.id']+');'},
        remove:{
            text:'删除Condition',
            link:'/conditionview/delete/'+cond.id,
            title:'title',
        }
    };
    var actions = html_actions(conf);
    return [
        '<div class="condition">',
            '<b>Name:</b>&nbsp;',
            cond.name,
            '<br>',
            '<b>A:</b>&nbsp;',
            cond.voltage_a,
            '<br>',
            '<b>B:</b>&nbsp;',
            cond.voltage_b,
            '<br>',
            '<p>',
            cond.readme,
            '</p>',
            '<div class="condition-actions">',
            actions,
            '</div>',
        '</div>'
    ].join("");
}


function init_table_header(table, headers)
{
	var header = table.find('thead tr');
	headers.forEach(function(item, index, arr){
		header.append('<th>'+item+'</th>');
	});
}


function edit_unit(unit_id)
{
    console.log('edit_unit');
    //http://127.0.0.1:8000/checkunitview/show/1
    var profile = getShowID();
    if( profile != null ){
        // window.open("/checkunitview/add?profile="+profile);
        window.location.href = "/checkunitview/edit/"+unit_id+"?profile=" + profile;
    }
}

function edit_selector(selector_id)
{
    console.log('edit_selector');
    //http://127.0.0.1:8000/checkunitview/show/1

}

function edit_condition(condition_id, unit_id, selector_id)
{
	var profile = getShowID();
    if( profile != null ){
        // window.open("/checkunitview/add?profile="+profile);
        window.location.href = "/conditionview/edit/"+condition_id+"?profile=" + profile + '&unit=' + unit_id + '&selector=' + selector_id;
    }
}

function add_condition(selector_id)
{
    var profile = getShowID();
    if( profile != null ){
        // window.open("/checkunitview/add?profile="+profile);

        window.location.href = "/conditionview/add?selector="+selector_id+"&profile=" + profile;
    }
}